<template>
  <a-modal v-model:visible="isVisible" title="运营日报." @ok="ok">
    <a-spin :spinning="loading">
      <a-form
        ref="formRef"
        layout="horizontal"
        name="dynamic_form_nest_item"
        @finish="finish"
        :model="dynamicValidateForm"
        :labelAlign="right"
        :label-col="lableStyle"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-item label="平台" name="platformId" style="margin-bottom: 5px" required>
          <a-popconfirm
            title="切换平台会导致当前内容清空，确定吗?"
            :visible="platformComfirmShow"
            ok-text="确定"
            cancel-text="取消"
            @confirm="confirmChange(true)"
            @cancel="confirmChange(false)"
          >
            <JDictSelectTag v-model:value="dynamicValidateForm.platformId" dictCode="yyc_business_platform,name,id" />
          </a-popconfirm>
        </a-form-item>
        <a-form-item label="店铺" name="storeId" style="margin-bottom: 5px" required>
          <JDictSelectTag v-model:value="dynamicValidateForm.storeId" compType="CompTypeEnum.Select" :dictCode="storeDictStr" />
        </a-form-item>
        <a-form-item label="时间" name="datatime" style="margin-bottom: 5px">
          <a-date-picker v-model:value="dynamicValidateForm.datatime" placeholder="日报时间" required valueFormat="YYYY-MM-DD" />
        </a-form-item>
        <div style="height: 500px; overflow: auto">
          <template v-for="(reportItem, index) in dynamicValidateForm.reportItems" :key="reportItem.dailyItemId">
            <a-form-item
              :label="reportItem.dailyText"
              :name="['reportItems', index, 'value']"
              style="margin-bottom: 5px"
              :rules="{
                required: false,
                message: '不能为空',
              }"
            >
              <a-form-item :name="['reportItems', index, 'dailyItemId']" style="display: none">
                <a-input v-model:value="reportItem.dailyItemId" placeholder="dailyItemId" />
              </a-form-item>
              <a-input v-model:value="reportItem.value" placeholder="value" />
            </a-form-item>
          </template>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script lang="ts" setup>
  interface DailyReport {
    platformId: string;
    goodsId: string;
    storeId: string;
    datatime: string;
    reportItems: ReportItem[];
  }

  interface ReportItem {
    dailyItemId: string;
    dailyText?: string;
    value: string;
    platformId?: string;
    goodsId?: string;
    datatime: string;
    storeId?: string;
  }

  import { computed, reactive, ref, toRaw, watch, onMounted } from 'vue';
  import { JDictSelectTag } from '/@/components/Form';
  import type { FormInstance } from 'ant-design-vue';
  import { list as dailyItemList } from '../../setting/dailyItem/DailyItem.api';
  import { list as platformList } from '../../setting/businessplatform/BusinessPlatform.api';
  import { saveOrUpdate } from '../PlatformDaily.api';

  const emit = defineEmits(['update:visible', 'onOk']);
  const props = defineProps({ visible: Boolean });
  const formRef = ref<FormInstance>();
  const loading = ref(false);
  const lableStyle = { style: { width: '100px' } };
  const platformComfirmShow = ref(false);
  let platformId = '';

  const dynamicValidateForm = reactive<DailyReport>({
    platformId: '',
    goodsId: '',
    storeId: '',
    datatime: '',
    reportItems: [],
  });

  const storeDictStr = ref('yyc_store,name,id');

  const isVisible = computed({
    get() {
      return props.visible;
    },
    set(value) {
      emit('update:visible', value);
    },
  });

  watch(dynamicValidateForm, () => {
    if (platformId != null && platformId !== '') {
      if (platformId !== dynamicValidateForm.platformId) {
        platformComfirmShow.value = true;
      }
    } else {
      platformId = dynamicValidateForm.platformId;
      confirmChange(true);
    }
    storeDictStr.value = 'yyc_store,name,id,platform_id="' + platformId + '"';
  });

  onMounted(() => {
    platformList({}).then((result) => {
      dynamicValidateForm.platformId = result.records[0].id;
    });
  });

  function updateDailyItems(platFormId: string) {
    loading.value = true;
    dailyItemList({ platformId: platFormId, pageSize: 100 }).then((result) => {
      dynamicValidateForm.reportItems = [];
      result.records.forEach((item) => {
        dynamicValidateForm.reportItems.push({
          dailyItemId: item.id,
          dailyText: item.name,
          datatime: '',
          value: '',
        });
      });
      loading.value = false;
    });
  }

  function confirmChange(isConfirm: boolean) {
    if (!isConfirm) {
      dynamicValidateForm.platformId = platformId;
    } else {
      platformId = dynamicValidateForm.platformId;
    }
    platformComfirmShow.value = false;
    updateDailyItems(platformId);
  }

  function ok() {
    formRef.value?.validate().then(() => {
      let sumbitObj: ReportItem[] = [];
      let formObj = toRaw(dynamicValidateForm);
      formObj.reportItems.forEach((item) => {
        if (item.value.trim() === '') return;
        sumbitObj.push({
          dailyItemId: item.dailyItemId,
          value: item.value,
          datatime: dynamicValidateForm.datatime + ' 00:00:00',
          platformId: formObj.platformId,
          goodsId: formObj.goodsId,
          storeId: formObj.storeId,
        });
      });
      saveOrUpdate(sumbitObj, false).then(() => {
        isVisible.value = false;
        emit('onOk');
      });
    });
  }
</script>
